//
//  InPutCodeVC.m
//  DriverClient
//
//  Created by 吕晶 on 2020/8/4.
//  Copyright © 2020 吕晶. All rights reserved.
//

#import "InPutCodeVC.h"
#import "JQUnitField.h"
#import "CustomSuccessAlertView.h"

@interface InPutCodeVC ()

@property (nonatomic, strong) JQUnitField *codeField;
@property (nonatomic, strong) UILabel *timeLab;
@property (nonatomic, strong) UILabel *llab;
@property (nonatomic, strong) UIButton *yuYinBtn;
@property (nonatomic, strong) UIButton *reBtn;

@end

@implementation InPutCodeVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = HexColor(0xffffff);
    [self configUI];
}

- (void)configUI {
    UILabel *titleLab = [[UILabel alloc] initWithFrame:CGRectMake(15, 30, ScreenW - 30, 21)];
    titleLab.font = BoldFontOfSize(20);
    titleLab.text = self.isEmail ? @"验证码已发送至邮箱" : @"验证码已发送至手机";
    titleLab.textColor = HexColor(0x2B2C44);
    [self.view addSubview:titleLab];
    
    UILabel *remarkLab = [[UILabel alloc] initWithFrame:CGRectMake(15, 10 + titleLab.nim_bottom, ScreenW - 30, 15)];
    remarkLab.font = [UIFont systemFontOfSize:14];
    if (self.isEmail) {
        remarkLab.text = [NSString stringWithFormat:@"当前邮箱地址：%@",self.phone];
    }else {
        remarkLab.text = [NSString stringWithFormat:@"+86 %@",self.phone];
    }
    remarkLab.textColor = HexColor(0x9C9DB3);
    [self.view addSubview:remarkLab];
    
    UILabel *descLab = [[UILabel alloc] initWithFrame:CGRectMake(15, 30 + remarkLab.nim_bottom, ScreenW - 30, 15)];
    descLab.font = [UIFont systemFontOfSize:14];
    descLab.text = @"请输入验证码";
    descLab.textColor = HexColor(0x2B2C44);
    [self.view addSubview:descLab];
    
    self.codeField = [[JQUnitField alloc]initWithFrame:CGRectMake(15, descLab.nim_bottom + 20, ScreenW - 30, 40)];
    self.codeField.textFont = [UIFont boldSystemFontOfSize:18];
    self.codeField.defaultKeyboardType = JQKeyboardTypeNumberPad;
    self.codeField.textColor = HexColor(0x333333);
    self.codeField.inputUnitCount = 4;
//    self.codeField.delegate = self;
    self.codeField.underline = YES;
    self.codeField.unitSpace = 20.0;
    self.codeField.trackTintColor = HexColor(0xC7C7CC);
    self.codeField.tintColor = HexColor(0xC7C7CC);
    [self.view addSubview:self.codeField];
    [self.codeField addTarget:self action:@selector(codeFieldTextChanged:) forControlEvents:UIControlEventEditingChanged];
    
    self.timeLab = [[UILabel alloc] initWithFrame:CGRectMake(15, self.codeField.nim_bottom + 20, ScreenW - 30, 15)];
    self.timeLab.font = [UIFont systemFontOfSize:14];
    self.timeLab.text = @"60S 后重新发送验证码 或 通过其他途径验证";
    self.timeLab.textColor = HexColor(0x9C9DB3);
    [self.view addSubview:self.timeLab];
    
    [self reClick];
    
    if (!self.isEmail) {
        self.llab = [[UILabel alloc] initWithFrame:CGRectMake(15, self.timeLab.nim_bottom + 20, ScreenW - 30, 0)];
        self.llab.text = @"收不到验证码？请先确认手机是否安装短信拦截软件或是否欠费停机。若均不是，请在尝试以下方式";
        self.llab.font = [UIFont systemFontOfSize:14];
        self.llab.textColor = HexColor(0x9C9DB3);
        self.llab.numberOfLines = 2;
        [self.llab sizeToFit];
        [self.view addSubview:self.llab];
        
        self.yuYinBtn = [[UIButton alloc] initWithFrame:CGRectMake(15, self.llab.nim_bottom + 10, [FactoryMethod sizeWithText:@"语音获取" font:[UIFont systemFontOfSize:14] maxSize:CGSizeMake(0, 0)].width, 15)];
        [self.yuYinBtn setTitle:@"语音获取" forState:0];
        [self.yuYinBtn setTitleColor:Color_ThemeColor forState:0];
        self.yuYinBtn.titleLabel.font = [UIFont systemFontOfSize:14];
        [self.yuYinBtn addTarget:self action:@selector(yuYinClick) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:self.yuYinBtn];
        self.yuYinBtn.hidden = YES;
        
        self.reBtn = [[UIButton alloc] initWithFrame:CGRectMake(self.yuYinBtn.nim_right + 30, self.llab.nim_bottom + 10, [FactoryMethod sizeWithText:@"重新获取验证码" font:[UIFont systemFontOfSize:14] maxSize:CGSizeMake(0, 0)].width, 15)];
        [self.reBtn setTitle:@"重新获取验证码" forState:0];
        [self.reBtn setTitleColor:Color_ThemeColor forState:0];
        self.reBtn.titleLabel.font = [UIFont systemFontOfSize:14];
        [self.reBtn addTarget:self action:@selector(reClick) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:self.reBtn];
    }
}

- (void)yuYinClick {
    
}

- (void)reClick {
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    if (self.isEmail) {
        [dic setObject:self.phone forKey:@"email"];
    }else {
        [dic setObject:self.phone forKey:@"phone"];
    }
    [MBProgressHUD leShowHUDWithMessage:@"请求中" activity:YES];
    [HttpRequest PostWithApi:self.isEmail ? LogisticsSupplierGetNewEmailCode : LogisticsSupplierGetNewPhoneCode params:dic progress:^(NSProgress * _Nonnull progress) {

    } success:^(NSURLSessionDataTask * _Nonnull operation, id  _Nonnull responseObject, BOOL code, NSInteger errorCode) {
        if (code) {
            [MBProgressHUD leShowSuccessHUDAddedTo:self.view message:@"验证码获取成功"];
            [self.codeField becomeFirstResponder];
        }
    } fail:^(NSError * _Nonnull error) {

    }];
    [self timeStart];
}

- (void)codeFieldTextChanged:(JQUnitField *)filed{
    if (filed.text.length >= 4) {
        [filed resignFirstResponder];
        //请求接口
        [self requestForCommit];
    }
}

- (void)requestForCommit {
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    if (self.isEmail) {
        [dic setObject:self.phone forKey:@"email"];
    }else {
        [dic setObject:self.phone forKey:@"phone"];
    }
    [dic setObject:self.codeField.text forKey:@"code"];
    [HttpRequest PostWithApi:self.isEmail ? LogisticsSupplierModifyEmail : LogisticsSupplierModifyPhone params:dic progress:^(NSProgress * _Nonnull progress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull operation, id  _Nonnull responseObject, BOOL code, NSInteger errorCode) {
        if (code) {
            CustomSuccessAlertView *alert = [CustomSuccessAlertView new];
            alert.text = self.isEmail ? @"邮箱修改成功" : @"手机号修改成功";
            __weak_self;
            alert.finishBlock = ^{
                if (weakself.isEmail) {
                    [weakself.rt_navigationController popToViewController:weakself.rt_navigationController.rt_viewControllers[1] animated:YES complete:nil];
                }else {
                    [User logoutSuccess];
                }
            };
            [alert showInView:MAIN_WINDOW];
        }
    } fail:^(NSError * _Nonnull error) {
        
    }];
}

- (void)timeStart{
    self.llab.hidden = NO;
    self.yuYinBtn.hidden = NO;
    self.reBtn.hidden = NO;
    [self.codeField becomeFirstResponder];
    __block int timeout = 60; //倒计时时间
    /**
     *  gcd异步处理倒计时控件
     */
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout<0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                self.reBtn.userInteractionEnabled = YES;
                [self.reBtn setTitleColor:Color_ThemeColor forState:UIControlStateNormal];
            });
        }else{
            int seconds = timeout;
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                self.reBtn.userInteractionEnabled = NO;
                NSString *strTime = [NSString stringWithFormat:@"%d S 后重新发送验证码 或 通过其他途径验证",seconds];
                self.timeLab.text = strTime;
                [self.reBtn setTitleColor:HexColor(0x2B2C44) forState:UIControlStateNormal];
            });
            timeout--;
        }
    });
    dispatch_resume(_timer);
}

@end
